﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace SS2TC.Speech
{
    public abstract class AudioStream
    {
        protected NativeMethods.WAVEFORMATEX nativeWaveFormat;

        protected byte[] waveData;

        protected NativeMethods.WAVEHDR waveHeader;

        protected AudioStream(WaveFormat waveFormat) 
        {
            nativeWaveFormat.wFormatTag = (short)waveFormat.WaveFormatTag;
            nativeWaveFormat.wBitsPerSample = (short)waveFormat.BitsPerSample;
            nativeWaveFormat.nChannels = (short)waveFormat.Channels;
            nativeWaveFormat.nSamplesPerSec = waveFormat.SamplingRate;
            nativeWaveFormat.nAvgBytesPerSec = waveFormat.AverageBytesPerSecond;
            nativeWaveFormat.nBlockAlign = waveFormat.BlockSize;
            nativeWaveFormat.cbSize = 0;
        }

        /// <summary>
        /// Open the binaryWriter.
        /// </summary>
        protected abstract void Open();

        /// <summary>
        /// Safely close the binaryWriter.
        /// </summary>
        public abstract void Close();

        protected static IntPtr GetIntPtr(object reference)
        {
            GCHandle handle = GCHandle.Alloc(reference, GCHandleType.Pinned);
            IntPtr dataPointer;

            try
            {
                dataPointer = handle.AddrOfPinnedObject();
            }
            finally
            {
                if (handle.IsAllocated)
                {
                    handle.Free();
                }
            }

            return dataPointer;
        }
    }
}
